/**
 * 
 */
var Bodystm= window.Bodystm = Bodystm || {};
Bodystm.BedManage=function() {
	  var self = this;
	  

};
Bodystm.BedManage.prototype={
	addBasicInfo:function (){
		$(".mainArea").html('<div id="bedstatistic" style="height:130px;width:100%;margin-left:10px;"><ul style="list-style:none;padding:0px;'+
				'margin:0px;"><li class="statisticLi" ><span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px; color: orange;">'+
				'<span class="highcount"></span><span style="font-size: 14px; color: #FFFFFF">位</span></span><span style="display: block; width: 140px; '+
				'text-align: center; font-size: 14px; color: #FFFFFF">患者体温过高</span></li><li class="statisticLi"><span style="margin-left:46px; width: 140px;'+
				' text-align: center; font-size: 48px; color: #1295FE;"><span class="lowcount"></span><span style="font-size: 14px; color: #FFFFFF">位</span></span>'+
				'<span style="display: block; width: 140px; text-align: center; font-size: 14px; color: #FFFFFF">患者体温过低</span></li><li class="statisticLi">'+
				'<span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px; color: #FFFFFF;"><span class="notemptycount"></span><span style="font-size: 14px;'+
				' color: #FFFFFF">位</span></span><span style="display: block; width: 140px; text-align: center; font-size: 14px; color: #FFFFFF">患者入住</span></li>'+
				'<li class="statisticLi"><span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px; color: #FFFFFF;">'+
				'<span class="emptycount"></span><span style="font-size: 14px; color: #FFFFFF">个</span></span><span style="display: block; width: 140px; text-align: center;'+
				' font-size: 14px; color: #FFFFFF">床位空置</span></li><li class="statisticLi"><span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px;'+
				' color: #FFFFFF;"><span class="totalcount"></span><span style="font-size: 14px; color: #FFFFFF">个</span></span><span style="display: block; width: 140px; '+
				'text-align: center; font-size: 14px; color: #FFFFFF">当前总计床位</span></li>'+
				//添加去噪设置（是否mean）
				'<li style="height: 84px;width: 250px;margin: 46 40 0 10;display: inline;float: right;color:white">'
				+'<p style="display:inline;cursor:pointer;"onclick="location.reload(true)">刷新界面</p>&nbsp;|&nbsp;<p style="display:inline">报警设置</p>'
				+'<input type="radio" name="arg4ifwarn" value="1" style="margin:10px;cursor:pointer;" id="radioyes" onchange="setting4ifwarn=true;">是'
				+'<input type="radio" name="arg4ifwarn" value="0" style="margin:10px;cursor:pointer;" id="radiono" onchange="setting4ifwarn=false;">否'
				//+'<a href="javascript:void(0);" onclick="updateArg()" style="color: #1295FE;margin-left:20px;">修改</a>'
				+'</li>'+
				//'<li class="btnAddBedLi4Deg"><div class="btnDiv4Deg" onclick="addBed()"><span class="btnSpan4Deg" '+
				//'style="background: url(../images/icon_add_sickbed_small.png) no-repeat;">添加床位</span></div></li><li class="btnAddBedLi4Deg">'+
				//'<div class="btnDiv4Deg" onclick="addPatient4btn()"><span class="btnSpan4Deg" style="background: url(../images/icon_add_patient_small.png) no-repeat;">患者入住</span></div></li>'+
				'</ul></div>'+
				'<div class="bedsArea"><ul id="bedList" style="list-style:none;padding:0px;margin:0px;"></ul></div>');
		if(setting4ifwarn){//ifwarning//setting4ifwarn
			$("#radioyes").attr("checked","true");		
		}else{
			$("#radiono").attr("checked","true");
		}
	}
}
//==============全局变量定义=========================
var timer4FreshBeds=null;//床位数据定时刷新计时器
var dataArr4ECG=[];//元素为数组，用于存放心电数据点//元素为对象，有心电数据等属性
var oximetryWaveform={};//血氧波形对象
var respWaveform={};//呼吸波形对象
var bloodPressureWaveform={};//连续血压波形对象
Bodystm.DataType={
		OXIMETRY:"00",
		ECG:"01",
		BLOODPRESSURE:"02",
		RESP:"03",
		TEMPERATURE:"04"
};
var screenResolutionX=window.screen.width;//1366;//屏幕横向分辨率
var screenWidth=308.80;//355.6;//mm 屏幕宽度
var vWaveform4Ecg=25;
var vWaveform4Oxi=25;
var vWaveform4Pwv=25;
var vWaveform4Resp=6.25;
var bufferTime=5;//各种波形数据缓存时间长度为5s
var buffer_config_bufferNum=0;//50;
//==============全局变量定义 END=========================
$(document).ready(function(){
	$(".menulist").css("height",document.body.scrollHeight-60);
	$(".mainArea").css("height",document.body.scrollHeight-60).css("width",document.body.scrollWidth-120);
	getBedsData();
	startAutoFresh();
	//startShowEcg();//孙悟空那个调试用的示例
	//startWebsocket();
	addEcgCharts();
	initBedEvent();
});
/**
 * 初始化床位各种点击事件
 */
function initBedEvent(){
	//点击床位名称弹出设置窗口
	initPatientNameEvent();
	initBedNameEvent();
	//点击血氧饱和度数值显示血氧波形窗口 spo2
	initOximetryEvent();
	//点击血压数值显示连续血压波形窗口 bp pwv
	initPWVEvent();
	//点击呼吸数值显示呼吸波形窗口 resp
	initRespEvent();
	initEcgChannelEvent();
}
/**
 * 初始化血氧波形显示相关事件
 */
function initOximetryEvent(){
	$(".bedDiv6").unbind("click");
	$(".bedDiv6").click(function(e){
		var html='<div class="oximetryForm"><div class="waveformDiv"></div></div>';
		var title=$(e.target).closest('.bedDiv6').siblings('.bedDiv1').find(".bedNameDiv").text()+"血氧波形：";
		//页面层
		layer.open({
		  type: 1,
		  title:title,
		  skin: 'layui-layer-rim', //加上边框
//		  area: ['600px', '450px'], //宽高
		  area: ['450px', '250px'], //宽高
		  content: html,
		  success: function(layero, index){
			//以下代码应该放到layer加载完以后，因为layer加载是异步的，会先执行以下代码
			var waveformDiv=$(".waveformDiv")[0];
			console.log(waveformDiv);
			oximetryWaveform.chart=echarts.init(waveformDiv);
			oximetryWaveform.data=[];
			var oximetryData=oximetryWaveform.data;
			var dataTemp=[];
			var timer=null;
			var curIndex=0;
			var pointNumPer200ms=5;//19//50;
			
			oximetryWaveform.dataTemp=dataTemp;//用于存放ws接收到的心电数据        
			oximetryWaveform.max=6000;
			oximetryWaveform.min=-6000;
			var width_px=323;//323;//绘图区域宽度，单位为像素
			width_px=getChartXmax(screenResolutionX,screenWidth,380);
			width_px=380;
			var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Oxi);
			oximetryWaveform.bufferSize=targetSampleRate*bufferTime;
			//pointNumPer200ms=3;//targetSampleRate/8;
			//var intervalSeconds=50;//1000/8;
			oximetryWaveform.intervalSeconds=50;
			pointNumPer200ms=Math.round(targetSampleRate*oximetryWaveform.intervalSeconds/1000);
			for (var i = 0; i < width_px; i++) {
				oximetryData.push([i,1]);//randomData()
		    }
			var option = {
			    /*title: {
			        text: '动态数据 + 时间坐标轴'
			    },*/
				grid:{
				    x:16,
				    y:0,
				    x2:17,
				    y2:0
				  },
			    //width:"auto",
			    xAxis: {
			        type: 'value',
			        splitLine: {
			            show: false
			        },
			        min:0,
			        max:width_px
			    },
			    yAxis: {
			        type: 'value',
			        boundaryGap: [0, '100%'],
			        splitLine: {
			            show: false
			        },
			        min:-6000,//-2,
			        max:6000//2
			    },
			    series: [{
			        name: '模拟数据',
			        type: 'line',
			        showSymbol: false,
			        hoverAnimation: false,
			        itemStyle : {  
		                normal : {  
		                    lineStyle:{  
		                        color:'#00a8ff'  
		                    }  
		                }  
		            },
			        data: oximetryData
			    }]
			};
			oximetryWaveform.chart.setOption(option);
			oximetryWaveform.ifBuffered=false;
			oximetryWaveform.drawFunc=function(){
				if(oximetryWaveform.ifBuffered==false){
					if(oximetryWaveform.dataTemp.length>=oximetryWaveform.bufferSize){//缓存2s数据
						oximetryWaveform.ifBuffered=true;
					}
					oximetryWaveform.timer=setTimeout(oximetryWaveform.drawFunc,oximetryWaveform.intervalSeconds);
					return;
				}
				var intervalTemp=oximetryWaveform.intervalSeconds;
				if(oximetryWaveform.dataTemp.length-buffer_config_bufferNum>oximetryWaveform.bufferSize){//缓存2s数据
					//oximetryWaveform.intervalSeconds-=1;
					intervalTemp=oximetryWaveform.intervalSeconds-15;
					
				}else if(oximetryWaveform.dataTemp.length+buffer_config_bufferNum<oximetryWaveform.bufferSize){
					//oximetryWaveform.intervalSeconds+=1;
					intervalTemp=oximetryWaveform.intervalSeconds+1;
				}
//				oximetryWaveform.intervalSeconds=intervalTemp;
				oximetryWaveform.timer=setTimeout(oximetryWaveform.drawFunc,intervalTemp);
				var tmp;
				var ifx0=false;//是否重新轮到绘制x=0处的图像
				for (var i = 0; i < pointNumPer200ms; i++) {//curIndex+
					tmp=dataTemp.shift();
//					oximetryData[i]=[i,tmp==undefined?0:tmp];
					tmp=tmp==undefined?0:tmp;
					if(tmp>oximetryWaveform.max+2000){
						tmp=oximetryWaveform.max+2000;
					}else if(tmp<oximetryWaveform.min-2000){
						tmp=oximetryWaveform.min-2000;
					}
//					oximetryData[i]=[i,tmp];
					if(curIndex>=width_px){
						curIndex=0;
						ifx0=true;
					}
					oximetryData[curIndex]=[curIndex,tmp];
					curIndex++;
			    }
				//为了防止前端后端数据速度不一致，每次读取缓存里所有
				/*if(dataTemp.length==0){
					for (var i = curIndex; i < curIndex+pointNumPer200ms; i++) {
						oximetryData[i]=[i,0];
				    }
					curIndex+=pointNumPer200ms;
					if(curIndex>=width_px){
						curIndex=0;
						ifx0=true;
					}
				}else{
					while(true){
						tmp=dataTemp.shift();
						if(tmp==undefined){
							break;
						}
						oximetryData[curIndex]=[curIndex,tmp];
						curIndex++;
						if(curIndex>=width_px){
							curIndex=0;
							ifx0=true;
						}
					}
					
				}*/
//				curIndex+=pointNumPer200ms;
				/*oximetryData[curIndex]=undefined;
				oximetryData[curIndex+1]=undefined;
				if(curIndex>=width_px){
					curIndex=0;
					ifx0=true;
				}*/
				for(var i=0;i<10;i++){
					if(curIndex+i>=width_px){
						oximetryData[curIndex+i-width_px]=undefined;
					}else{
						oximetryData[curIndex+i]=undefined;
					}
				}
				var option={
					series: [{
			            data: oximetryData
			        }]	
				}
				if(ifx0){
					option.yAxis={
						min:oximetryWaveform.min-2000,
				        max:oximetryWaveform.max+2000
					}
				}
				oximetryWaveform.chart.setOption(option);
				
			}
//			oximetryWaveform.timer=setInterval(function(){
			oximetryWaveform.timer=setTimeout(oximetryWaveform.drawFunc,oximetryWaveform.intervalSeconds);
			
			//连接ws
			oximetryWaveform.mac=$(e.target).closest('.bedDiv').attr("mac");
			//initWebsocket(oximetryWaveform,oximetryWaveform.mac,Bodystm.DataType.OXIMETRY);
			initWebsocket4Oxiemetry(oximetryWaveform,oximetryWaveform.mac,Bodystm.DataType.OXIMETRY);
		  },
		  end:function(){
			  if(oximetryWaveform.timer){
				  clearInterval(oximetryWaveform.timer);
			  }
			  oximetryWaveform.dataTemp.splice(0);
			  oximetryWaveform.data.splice(0);
			  oximetryWaveform.ws.close();
		  }
		});
		
	});
}
/**
 * 初始化连续血压波形显示相关事件
 */
function initPWVEvent(){
	$(".bedDiv5").unbind("click");
	$(".bedDiv5").click(function(e){
		var html='<div class="oximetryForm"><div class="waveformDiv"></div></div>';
		var title=$(e.target).closest('.bedDiv5').siblings('.bedDiv1').find(".bedNameDiv").text()+"血压波形：";
		//页面层
		layer.open({
		  type: 1,
		  title:title,
		  skin: 'layui-layer-rim', //加上边框
//		  area: ['600px', '450px'], //宽高
		  area: ['450px', '250px'], //宽高
		  content: html,
		  success: function(layero, index){
			//以下代码应该放到layer加载完以后，因为layer加载是异步的，会先执行以下代码
			var waveformDiv=$(".waveformDiv")[0];
			console.log(waveformDiv);
			bloodPressureWaveform.chart=echarts.init(waveformDiv);
			bloodPressureWaveform.data=[];
			var pwvData=bloodPressureWaveform.data;
			var dataTemp=[];
			var timer=null;
			var curIndex=0;
			var pointNumPer200ms=5;//19//50;
			bloodPressureWaveform.dataTemp=dataTemp;//用于存放ws接收到的心电数据        
			bloodPressureWaveform.max=6000;
			bloodPressureWaveform.min=-6000;
			var width_px=323;//323;//绘图区域宽度，单位为像素
			width_px=380;
			var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Pwv);
			bloodPressureWaveform.bufferSize=targetSampleRate*bufferTime;
			bloodPressureWaveform.intervalSeconds=50;
			pointNumPer200ms=Math.round(targetSampleRate*bloodPressureWaveform.intervalSeconds/1000);
			for (var i = 0; i < width_px; i++) {
				pwvData.push([i,1]);//randomData()
		    }
			var option = {
			    /*title: {
			        text: '动态数据 + 时间坐标轴'
			    },*/
				grid:{
				    x:16,
				    y:0,
				    x2:17,
				    y2:0
				  },
			    //width:"auto",
			    xAxis: {
			        type: 'value',
			        splitLine: {
			            show: false
			        },
			        min:0,
			        max:width_px
			    },
			    yAxis: {
			        type: 'value',
			        boundaryGap: [0, '100%'],
			        splitLine: {
			            show: false
			        },
			        min:-6000,//-2,
			        max:6000//2
			    },
			    series: [{
			        name: '模拟数据',
			        type: 'line',
			        showSymbol: false,
			        hoverAnimation: false,
			        itemStyle : {  
		                normal : {  
		                    lineStyle:{  
		                        color:'#00FF00'  
		                    }  
		                }  
		            },
			        data: pwvData
			    }]
			};
			bloodPressureWaveform.chart.setOption(option);
			bloodPressureWaveform.ifBuffered=false;
			bloodPressureWaveform.drawFunc=function(){
				if(bloodPressureWaveform.ifBuffered==false){
					if(bloodPressureWaveform.dataTemp.length>=bloodPressureWaveform.bufferSize){//缓存2s数据
						bloodPressureWaveform.ifBuffered=true;
					}
					bloodPressureWaveform.timer=setTimeout(bloodPressureWaveform.drawFunc,bloodPressureWaveform.intervalSeconds);
					return;
				}
				var intervalTemp=bloodPressureWaveform.intervalSeconds;
				if(bloodPressureWaveform.dataTemp.length-buffer_config_bufferNum>bloodPressureWaveform.bufferSize){//缓存2s数据
					//bloodPressureWaveform.intervalSeconds-=1;
					intervalTemp=bloodPressureWaveform.intervalSeconds-1;
					
				}else if(bloodPressureWaveform.dataTemp.length+buffer_config_bufferNum<bloodPressureWaveform.bufferSize){
					//bloodPressureWaveform.intervalSeconds+=1;
					intervalTemp=bloodPressureWaveform.intervalSeconds+2;
				}
				bloodPressureWaveform.timer=setTimeout(bloodPressureWaveform.drawFunc,bloodPressureWaveform.intervalSeconds);
				var tmp;
				var ifx0=false;//是否重新轮到绘制x=0处的图像
				for (var i = curIndex; i < curIndex+pointNumPer200ms; i++) {
					tmp=dataTemp.shift();
//					pwvData[i]=[i,tmp==undefined?0:tmp];
					tmp=tmp==undefined?0:tmp;
					if(tmp>bloodPressureWaveform.max){
						tmp=bloodPressureWaveform.max;
					}else if(tmp<bloodPressureWaveform.min){
						tmp=bloodPressureWaveform.min;
					}
					pwvData[i]=[i,tmp];
					/*if(curIndex>=width_px){
						curIndex=0;
					}
					pwvData[curIndex]=[curIndex,tmp];
					curIndex++;*/
			    }
				curIndex+=pointNumPer200ms;
				pwvData[curIndex]=undefined;
				pwvData[curIndex+1]=undefined;
				if(curIndex>=width_px){
					curIndex=0;
					ifx0=true;
				}
				var option={
					series: [{
			            data: pwvData
			        }]	
				}
				if(ifx0){
					option.yAxis={
							min:bloodPressureWaveform.min,
					        max:bloodPressureWaveform.max
					}
				}
				bloodPressureWaveform.chart.setOption(option);
			}
			bloodPressureWaveform.timer=setTimeout(bloodPressureWaveform.drawFunc,bloodPressureWaveform.intervalSeconds);
			
			//连接ws
			bloodPressureWaveform.mac=$(e.target).closest('.bedDiv').attr("mac");
			//initWebsocket(oximetryWaveform,oximetryWaveform.mac,Bodystm.DataType.OXIMETRY);
			initWebsocket4Oxiemetry(bloodPressureWaveform,bloodPressureWaveform.mac,Bodystm.DataType.BLOODPRESSURE);
		  },
		  end:function(){
			  if(bloodPressureWaveform.timer){
				  clearInterval(bloodPressureWaveform.timer);
			  }
			  bloodPressureWaveform.dataTemp.splice(0);
			  bloodPressureWaveform.data.splice(0);
			  bloodPressureWaveform.ws.close();
		  }
		});
		
	});
}
/**
 * 初始化呼吸波形显示相关事件
 */
function initRespEvent(){
	$(".bedDiv3").unbind("click");
	$(".bedDiv3").click(function(e){
		var html='<div class="oximetryForm"><div class="waveformDiv"></div></div>';
		var title=$(e.target).closest('.bedDiv3').siblings('.bedDiv1').find(".bedNameDiv").text()+"呼吸波形：";
		//页面层
		layer.open({
		  type: 1,
		  title:title,
		  skin: 'layui-layer-rim', //加上边框
//		  area: ['600px', '450px'], //宽高
		  area: ['450px', '250px'], //宽高
		  content: html,
		  success: function(layero, index){
			//以下代码应该放到layer加载完以后，因为layer加载是异步的，会先执行以下代码
			var waveformDiv=$(".waveformDiv")[0];
			console.log(waveformDiv);
			respWaveform.chart=echarts.init(waveformDiv);
			respWaveform.data=[];
			var respData=respWaveform.data;
			var dataTemp=[];
			var timer=null;
			var curIndex=0;
			var pointNumPer200ms=5;//19//50;
			respWaveform.dataTemp=dataTemp;//用于存放ws接收到的心电数据        
			var width_px=323;//323;//绘图区域宽度，单位为像素
			//width_px=getChartXmax(screenResolutionX,screenWidth,380);
			width_px=380;
			var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Resp);
			pointNumPer200ms=Math.round(targetSampleRate/8);
			var intervalSeconds=1000/8;
			respWaveform.bufferSize=targetSampleRate*bufferTime;
			respWaveform.intervalSeconds=1000/8;
			for (var i = 0; i < width_px; i++) {
				respData.push([i,1]);//randomData()
		    }
			var option = {
			    /*title: {
			        text: '动态数据 + 时间坐标轴'
			    },*/
				grid:{
				    x:16,
				    y:0,
				    x2:17,
				    y2:0
				  },
			    //width:"auto",
			    xAxis: {
			        type: 'value',
			        splitLine: {
			            show: false
			        },
			        min:0,
			        max:width_px
			    },
			    yAxis: {
			        type: 'value',
			        boundaryGap: [0, '100%'],
			        splitLine: {
			            show: false
			        },
			        min:0,
			        max:256
			    },
			    series: [{
			        name: '模拟数据',
			        type: 'line',
			        showSymbol: false,
			        hoverAnimation: false,
			        itemStyle : {  
		                normal : {  
		                    lineStyle:{  
		                        color:'#00FF00'  
		                    }  
		                }  
		            },
			        data: respData
			    }]
			};
			respWaveform.chart.setOption(option);
			respWaveform.ifBuffered=false;
			respWaveform.drawFunc=function(){
				if(respWaveform.ifBuffered==false){
					if(respWaveform.dataTemp.length>=respWaveform.bufferSize){//缓存2s数据
						respWaveform.ifBuffered=true;
					}
					respWaveform.timer=setTimeout(respWaveform.drawFunc,respWaveform.intervalSeconds);
					return;
				}
				var intervalTemp=respWaveform.intervalSeconds;
				if(respWaveform.dataTemp.length-buffer_config_bufferNum>respWaveform.bufferSize){//缓存2s数据
					//respWaveform.intervalSeconds-=1;
					intervalTemp=respWaveform.intervalSeconds-1;
					
				}else if(respWaveform.dataTemp.length+buffer_config_bufferNum<respWaveform.bufferSize){
					//respWaveform.intervalSeconds+=1;
					intervalTemp=respWaveform.intervalSeconds+48;
				}
//				respWaveform.intervalSeconds=intervalTemp;
				respWaveform.timer=setTimeout(respWaveform.drawFunc,intervalTemp);
				var tmp;
				//var ifx0=false;//是否重新轮到绘制x=0处的图像
				for (var i =0; i < pointNumPer200ms; i++) {
					tmp=dataTemp.shift();
//					respData[i]=[i,tmp==undefined?0:tmp];
					tmp=tmp==undefined?0:tmp;
					if(tmp>256){
						tmp=256;
					}else if(tmp<0){
						tmp=0;
					}
//					respData[i]=[i,tmp];
					if(curIndex>=width_px){
						curIndex=0;
					}
					respData[curIndex]=[curIndex,tmp];
					curIndex++;
			    }
//				curIndex+=pointNumPer200ms;
				/*respData[curIndex]=undefined;
				respData[curIndex+1]=undefined;
				if(curIndex>=width_px){
					curIndex=0;
					//ifx0=true;
				}*/
				for(var i=0;i<10;i++){
					if(curIndex+i>=width_px){
						respData[curIndex+i-width_px]=undefined;
					}else{
						respData[curIndex+i]=undefined;
					}
				}
				var option={
					series: [{
			            data: respData
			        }]	
				}
				/*if(ifx0){
					option.yAxis={
							min:bloodPressureWaveform.min,
					        max:bloodPressureWaveform.max
					}
				}*/
				respWaveform.chart.setOption(option);
			}
			respWaveform.timer=setTimeout(respWaveform.drawFunc,respWaveform.intervalSeconds);
			
			//连接ws
			respWaveform.mac=$(e.target).closest('.bedDiv').attr("mac");
			initWebsocket(respWaveform,respWaveform.mac,Bodystm.DataType.RESP);
		  },
		  end:function(){
			  if(respWaveform.timer){
				  clearInterval(respWaveform.timer);
			  }
			  respWaveform.dataTemp.splice(0);
			  respWaveform.data.splice(0);
			  respWaveform.ws.close();
		  }
		});
		
	});
}
function initEcgChannelEvent(){
	/*$(".ecgChannel").click(function(e){
		
	});*/
	$(".ecgChannel select").unbind("change");
	$(".ecgChannel select").change(function(e){
		var channel=$(this).val();
		var mac=$(e.target).closest('.bedDiv').attr("mac");
		/*if(channel==""){
			channel=0;
		}else if(){
			channel=1;
		}else{
			channel=2;
		}*/
		$.ajax({
			url:"changeEcgChannel.action",
			data:{
				mac:mac,
				channelType:parseInt(channel)
			},
			type:"post",
			dataType:"json",
			success:function(data){
				
			}
		});
	});
	//$(bed).find(".ecgChannel select").val(dom.ecgChannel);
}

//==============================病人相关=================================
/**
 * 病人入住
 * @param span
 */
function addPatient(span){
	layer.open({
        type: 1
        ,title: false //不显示标题栏false
        ,closeBtn: false
        ,area: '280px;'
        ,shade: 0.8
        ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
        ,btn: ['确定', '取消']
        ,btnAlign: 'c'
        ,moveType: 1 //拖拽模式，0或者1
        ,content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;"><span class="span4PatientName">姓名：</span><input class="patientNameInput"></div>'
        ,success: function(layero,index){
        	$(document).on('keydown', function(e){  //document为当前元素，限制范围，如果不限制的话会一直有事件
                if(e.keyCode == 13){
                	var bedid=$(span).closest(".bedDiv").attr("bedid");
        			var patientName=$(".patientNameInput").val();
        			if(""==patientName){
        				layer.msg("请填写病人姓名");
        				return;
        			}
        			$.ajax({
        				url:"../patient/addPatient.action",
        				data:{
        					name:patientName,
        					bedId:bedid
        				},
        				type:"post",
        				dataType:"json",
        				success:function(data){
        					var bedDiv=$(span).closest(".bedDiv");
        					var bedName=$(span).closest(".bedDiv").find(".bedNameDiv span").text();
        					var html='<span class="patientNameSpan" patientId="'+data.patientId+'" startTime="'+getNowFormatDate()+'">'+patientName+'</span><span>/</span><span class="bedNameSpan">'+bedName+'</span>';
        					$(span).closest(".bedDiv").find(".bedNameDiv").html(html);
        					$(span).closest(".bedDiv").find(".ecgChannel").show();
        					$(span).closest(".bedDiv").find(".sign1mv").show();
        					$(span).closest(".bedDiv").find(".bedStatusDiv").html("<ul></ul>");
        					initBedEvent();
        					addEcgChart(bedDiv,true);
        					layer.close(index);
        				}
        			});
        			
                }
            })
        }
		,btn1:function(index, layero){
			var bedid=$(span).closest(".bedDiv").attr("bedid");
			var patientName=$(".patientNameInput").val();
			if(""==patientName){
				layer.msg("请填写病人姓名");
				return false;
			}
			$.ajax({
				url:"../patient/addPatient.action",
				data:{
					name:patientName,
					bedId:bedid
				},
				type:"post",
				dataType:"json",
				success:function(data){
					var bedDiv=$(span).closest(".bedDiv");
					var bedName=$(span).closest(".bedDiv").find(".bedNameDiv span").text();
					
					var html='<span class="patientNameSpan" patientId="'+data.patientId+'" startTime="'+getNowFormatDate()+'">'+patientName+'</span><span>/</span><span class="bedNameSpan">'+bedName+'</span>';
					$(span).closest(".bedDiv").find(".bedNameDiv").html(html);
					$(span).closest(".bedDiv").find(".ecgChannel").show();
					$(span).closest(".bedDiv").find(".sign1mv").show();
					$(span).closest(".bedDiv").find(".bedStatusDiv").html("<ul></ul>");
					initBedEvent();
					addEcgChart(bedDiv,true);
					layer.close(index);
				}
			});
			
			return false;
		}
      });
	
}
function initPatientNameEvent(){
	$(".bedNameDiv .patientNameSpan").unbind("click");
	$(".bedNameDiv .patientNameSpan").click(function(e){
		var patientName=$(e.target).text();
		var patientId=$(e.target).attr('patientId');
		var rangeEnd=$(e.target).attr('rangeEnd');
		$.ajax({
			url:"../patient/getPatient.action",
			data:{
				id:patientId,
			},
			type:"post",
			dataType:"json",
			success:function(data){
				var html='<div class="updatePatientFormDiv">';
				html+='<fieldset class="layui-elem-field layui-field-title" style=""><legend>修改病人信息</legend></fieldset>';
				html+='<form class="layui-form updatePatientForm" action="../patient/updateBasicInfo.action">'
					
					+'<div class="layui-form-item">'
					+'<label class="layui-form-label">姓名</label>'
					+'<div class="layui-input-block" style="width:100px">'
					+'<input type="text" required name="name" lay-verify="required" autocomplete="off" placeholder="请输入姓名" class="layui-input" value="'+data.name+'">'
					+'<input type="text" hidden name="id" lay-verify="required" autocomplete="off" placeholder="请输入姓名" class="layui-input" value="'+data.id+'">'
					+'</div>'
					+'</div>'
					
					+'<div class="layui-form-item">'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">低温</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="rangeStart" lay-verify="number" autocomplete="off" placeholder="" class="layui-input" value="'+data.rangeStart+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">高温</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="rangeEnd" lay-verify="number" autocomplete="off" placeholder="" class="layui-input" value="'+data.rangeEnd+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">超高温</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="superHighDegree" lay-verify="number" autocomplete="off" placeholder="" class="layui-input" value="'+data.superHighDegree+'">'
					+'</div>'
					+'</div>'
					+'</div>'

					+'<div class="layui-form-item">'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">Spo2过低</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="spo2LowAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.spo2LowAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">Spo2过高</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="spo2HighAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.spo2HighAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'</div>'
					
					+'<div class="layui-form-item">'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">心率过低</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="hrLowAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.hrLowAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">心率过高</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="hrHighAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.hrHighAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'</div>'
					
					+'<div class="layui-form-item">'
					+'<div class="layui-input-block">'
					+'<button class="layui-btn" lay-submit="" lay-filter="updatePatient">立即提交</button>'
					+'<button type="reset" class="layui-btn layui-btn-primary" style="margin-left:70px">重置</button>'
					+'</div>'
					+'</div>'
					
					+'</form>';
				html+="</div>";
				//页面层
				var index4updatePatient=layer.open({
				  type: 1,
				  title:$(e.target).text(),
				  skin: 'layui-layer-rim', //加上边框
				  area: ['500px', '430px'], //宽高
				  content: html
				});
			}
		});
		
	});
}
function initBedNameEvent(){
	$(".bedNameDiv .bedNameSpan").unbind("click");
	$(".bedNameDiv .bedNameSpan").click(function(e){
		var bedId=$(e.target).closest('.bedDiv').attr('bedid');
		var bed=$(e.target).closest('.bedDiv');
		var patientName=$(bed).find(".patientNameSpan").text();
		var startTime=$(bed).find(".patientNameSpan").attr('startTime');
		var html='<div style="margin-left:8x;margin-right:8x;">';
//		html+='<button class="layui-btn patientOutBtn" style="margin-left:118px;margin-top:10px" lay-filter="">出院</button>';
		html+='<fieldset class="layui-elem-field" style="">'
			  +'<legend>患者信息</legend>'
			  +'<div class="layui-field-box">'
			  +'<span>患者姓名：'+patientName
			  +'</span><br><br>'
			  +'<span>入院时间：'+startTime
			  +'</span><br><br>'
			  +'<button class="layui-btn patientOutBtn" style="margin-left:15px;margin-top:0px" lay-filter="">出院</button>'
			    +'</div>'
			    +'</fieldset>'
		html+="</div>";
		//页面层
		layer.open({
		  type: 1,
		  title:$(e.target).text(),
		  skin: 'layui-layer-rim', //加上边框
		  area: ['300px', '230px'], //宽高
		  content: html,
		  success:function(){
			  $('.patientOutBtn').on('click', function(data){
				  patientOut(bedId,bed);
			  });
		  }
		});
	});
}
function patientOut(bedId,bed){
	layer.confirm('您确定要出院？', {
		  btn: ['确定','取消'] //按钮
		}, function(){
			$.ajax({
				type:"post",
				url:"patientOutBed.action",
				dataType:"json",
				data:{bedId:bedId},
				success:function(data){
					var bedName=$(bed).find(".bedNameDiv .bedNameSpan").text();
					var html='<span>'+bedName+'</span>';
					$(bed).find(".bedNameDiv").html(html);
					$(bed).find(".ecgChannel").hide();
					$(bed).find(".sign1mv").hide();
					$(bed).find(".chartDiv").html('');
					$(bed).find(".bedStatusDiv").html('<span onclick="addPatient(this)" class="btnAddPatient">病人入住</span>');
					layer.msg('出院成功！', {icon: 1,time: 2000});
					clearEcgData4PatientOut($(bed).attr('mac'));
				}
			})
			layer.closeAll();
		}, function(){
		  /*layer.msg('也可以这样', {
		    time: 20000, //20s后自动关闭
		    btn: ['明白了', '知道了']
		  });*/
		});
}
function clearEcgData4PatientOut(mac){
	for(var i=0;i<dataArr4ECG.length;i++){
		if(mac==dataArr4ECG[i].mac){
			clearInterval(dataArr4ECG[i].timer);
			dataArr4ECG[i].ws.close();
			dataArr4ECG[i]={};
			//dataArr4ECG.splice(i,1);
			break;
		}
	}
}
//==============================病人相关 END=================================
//开始自动刷新床位数据
function startAutoFresh(){
	clearTimeout(timer4FreshBeds);
	timer4FreshBeds = setInterval("getBedsData()", 5000);//自动刷新页面
}
//停止页面自动刷新
function stopAutoRefresh() {
	clearTimeout(timer4FreshBeds);
}
function getBedsData(){
	$.ajax({
		type:"post",
		url:"getCurBedsData.action",
		dataType:"json",
		data:{},
		success:function(e){
			var bedDivList=$("#bedList").find(".bedDiv");
			$(e).each(function(index,dom) {
				if(dom.status=='empty'){
					//dataArr4ECG.push({});这里怎么会有这句？头大
					return true;
				}
				var bed=bedDivList[index];//+1
				//清空状态
				$(bed).find(".bedStatusDiv ul").html("");
				var rangeStart=dom.rangeStart;
				var rangeEnd=dom.rangeEnd;
				var superHighDegree=dom.superHighDegree;
				var spo2LowAlarmValue=dom.spo2LowAlarmValue;
				var spo2HighAlarmValue=dom.ranspo2HighAlarmValuegeStart;
				var hrLowAlarmValue=dom.hrLowAlarmValue;
				var hrHighAlarmValue=dom.hrHighAlarmValue;
//				$(bed).find(".bedNameDiv span").text(dom.patientName+"-"+dom.name);//姓名和床位号
//				$(bed).find(".ecgChannel").text(dom.ecgChannel);
				$(bed).find(".ecgChannel select").val(dom.ecgChannel);
				$(bed).find(".breathRate").text((dom.respStatus==1&&dom.ecg)?dom.ecg.resp:"--");
				$(bed).find(".temperature").text((dom.temStatus==1&&dom.temperature)?dom.temperature.measureNum:"--");
				if(dom.temStatus==1&&dom.temperature){
					if(dom.temperature.measureNum<=rangeStart){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
											+'体温过低'+'</span></div></li>');
					}else if(dom.temperature.measureNum>=superHighDegree){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'体温超高'+'</span></div></li>');
					}else if(dom.temperature.measureNum>=rangeEnd){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'体温过高'+'</span></div></li>');
					}
					
				}
				$(bed).find(".bloodPressure").text((dom.bloStatus==1&&dom.bloodPressure)?dom.bloodPressure.highPressure+"/"+dom.bloodPressure.lowPressure:"--/--");
				//$(bed).find(".spo2").text((dom.oxiStatus==1&&dom.oximetry&&dom.oximetry.spo2>=0)?dom.oximetry.spo2:"--");
				var spo2="";
				if(dom.oxiStatus==1&&dom.oximetry&&dom.oximetry.spo2>=0){
					if(dom.oximetry.spo2>100){
						spo2=100;
					}else{
						spo2=dom.oximetry.spo2
					}
				}else{
					spo2="--";
				}
				$(bed).find(".spo2").text(spo2);
				if(dom.oxiStatus==1&&dom.oximetry&&dom.oximetry.spo2>=0){
					if(dom.oximetry.spo2>=spo2HighAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'血氧过高'+'</span></div></li>');
					}else if(dom.oximetry.spo2<=spo2LowAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'血氧过低'+'</span></div></li>');
					}
				}
				/*if(showPulseOrHr==0){
					$(bed).find(".heartRate").text((dom.oxiStatus==1&&dom.oximetry)?dom.oximetry.pulserate:"--");
				}else{
					$(bed).find(".heartRate").text((dom.ecgStatus==1&&dom.ecg)?dom.ecg.hr:"--");
				}*/
				if(dom.ecgStatus==1&&dom.ecg){
					$(bed).find(".heartRate").text(dom.ecg.hr);
					$(bed).find("bedDiv7 .unit").text("BPM");
					$(bed).find(".heartRate").css({color:'#30df1e'});
					if(dom.ecg.hr<=hrLowAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'心率过低'+'</span></div></li>');
					}else if(dom.ecg.hr>=hrHighAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'心率过高'+'</span></div></li>');
					}
				}else{
					$(bed).find(".heartRate").text((dom.oxiStatus==1&&dom.oximetry)?dom.oximetry.pulserate:"--");
					$(bed).find("bedDiv7 .unit").text("RPM");
					$(bed).find(".heartRate").css({color:'#00a8ff'});
				}
			});
		},
		error:function(){
			
		}
	})
}
/**
 * 初始化所有床位的心电图表
 */
function addEcgCharts(){
	var bedDivList=$("#bedList").find(".bedDiv");
	var i=0;
	$(bedDivList).each(function(index,dom) {
		//if(index==0)return true;//调试示例孙悟空相关
		if($(dom).attr("status")=='empty'){
			dataArr4ECG.push({});
			return true;
		}
		var bed=bedDivList[index];
		addEcgChart(bed);
	});
}
function addEcgChart(bedDiv,ifNotInit){
	var chartDiv=$(bedDiv).find(".chartDiv")[0];
	var chart=echarts.init(chartDiv);
	var ecgData=[];
	var dataTemp=[];
	var timer=null;
	var curIndex=0;
	var pointNumPer200ms=5;//19;//50;
	var width_px=323;//323;//绘图区域宽度，单位为像素
//	width_px=getChartXmax(screenResolutionX,screenWidth,380);
	width_px=380;
	var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Ecg);
	var intervalSeconds=50;//1000/8;
	pointNumPer200ms=Math.round(targetSampleRate*intervalSeconds/1000);
	//缓存数据相关
	var ecgChartJsonObj={
			chart:chart,
			data:ecgData,
			dataTemp:dataTemp,//用于存放ws接收到的心电数据
	        mac:$(bedDiv).attr("mac")
		}
	ecgChartJsonObj.bufferSize=targetSampleRate*bufferTime;
	ecgChartJsonObj.buffer_config_bufferNum=Math.round(ecgChartJsonObj.bufferSize/10);
	ecgChartJsonObj.intervalSeconds=50;
	ecgChartJsonObj.curIndex=0;
	for (var i = 0; i < width_px; i++) {
		ecgData.push([i,1]);//randomData()
    }
	var option = {
	    /*title: {
	        text: '动态数据 + 时间坐标轴'
	    },*/
	    /*tooltip: {
	        trigger: 'axis',
	        formatter: function (params) {
	            params = params[0];
	            var date = new Date(params.name);
	            return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1];
	        },
	        axisPointer: {
	            animation: false
	        }
	    },*/
		grid:{
		    x:16,
		    y:0,
		    x2:17,
		    y2:0
		  },
	    //width:"auto",
	    xAxis: {
	        type: 'value',
	        splitLine: {
	            show: false
	        },
	        min:0,
	        max:width_px//250
	    },
	    yAxis: {
	        type: 'value',
	        boundaryGap: [0, '100%'],
	        splitLine: {
	            show: false
	        },
	        min:-1,
	        max:3
	    },
	    series: [{
	        name: '模拟数据',
	        type: 'line',
	        showSymbol: false,
	        hoverAnimation: false,
	        /*lineStyle:{
	        	color:'green'
	        },*/
	        itemStyle : {  
                normal : {  
                    lineStyle:{  
                        color:'#00FF00'  
                    }  
                }  
            },
	        data: ecgData
	    }]
	};
	chart.setOption(option);
	ecgChartJsonObj.ifBuffered=false;
	ecgChartJsonObj.drawFunc=function(){
//		var curIndex=ecgChartJsonObj.curIndex;
		if(ecgChartJsonObj.ifBuffered==false){
			if(ecgChartJsonObj.dataTemp.length>=ecgChartJsonObj.bufferSize){//缓存2s数据
				ecgChartJsonObj.ifBuffered=true;
			}
			ecgChartJsonObj.timer=setTimeout(ecgChartJsonObj.drawFunc,ecgChartJsonObj.intervalSeconds);
			return;
		}
		var intervalTemp=ecgChartJsonObj.intervalSeconds;
		if(ecgChartJsonObj.dataTemp.length-buffer_config_bufferNum>ecgChartJsonObj.bufferSize){//缓存2s数据
			//ecgChartJsonObj.intervalSeconds-=1;
			intervalTemp=ecgChartJsonObj.intervalSeconds-2;
			
		}else if(ecgChartJsonObj.dataTemp.length+buffer_config_bufferNum<ecgChartJsonObj.bufferSize){
			//ecgChartJsonObj.intervalSeconds+=1;
			intervalTemp=ecgChartJsonObj.intervalSeconds+15;
		}
//		ecgChartJsonObj.intervalSeconds=intervalTemp;
		ecgChartJsonObj.timer=setTimeout(ecgChartJsonObj.drawFunc,intervalTemp);
		var tmp;
		for (var i = 0; i < pointNumPer200ms; i++) {
			tmp=dataTemp.shift();
			tmp=tmp==undefined?0:tmp;
			if(tmp>3){
				tmp=3;
			}else if(tmp<-1){
				tmp=-1;
			}
//			ecgData[i]=[i,tmp];
			if(curIndex>=width_px){
				curIndex=0;
			}
			ecgData[curIndex]=[curIndex,tmp];
			curIndex++;
	    }
		//为了防止前端后端数据速度不一致，每次读取缓存里所有
		/*if(dataTemp.length==0){
			for (var i = curIndex; i < curIndex+pointNumPer200ms; i++) {
				ecgData[i]=[i,0];
		    }
			curIndex+=pointNumPer200ms;
			if(curIndex>=width_px){
				curIndex=0;
			}
		}else{
			while(true){
				tmp=dataTemp.shift();
				if(tmp==undefined){
					break;
				}
				ecgData[curIndex]=[curIndex,tmp];
				curIndex++;
				if(curIndex>=width_px){
					curIndex=0;
				}
			}
			
		}*/
		/*curIndex+=pointNumPer200ms;
		ecgData[curIndex]=undefined;
		ecgData[curIndex+1]=undefined;
		if(curIndex>=width_px){
			curIndex=0;
		}*/
		for(var i=0;i<10;i++){
			if(curIndex+i>=width_px){
				ecgData[curIndex+i-width_px]=undefined;
			}else{
				ecgData[curIndex+i]=undefined;
			}
		}
		chart.setOption({
	        series: [{
	            data: ecgData
	        }]
	    });
		ecgChartJsonObj.curIndex=curIndex;
	}
	ecgChartJsonObj.timer=setTimeout(ecgChartJsonObj.drawFunc, ecgChartJsonObj.intervalSeconds);
	/*var ecgChartJsonObj={
			chart:chart,
			data:ecgData,
			dataTemp:dataTemp,//用于存放ws接收到的心电数据
			timer:timer,
	        mac:$(bedDiv).attr("mac")
		}*/
	if(ifNotInit){
		dataArr4ECG[parseInt($(bedDiv).attr('bedIndex'))]=ecgChartJsonObj;
	}else{
		dataArr4ECG.push(ecgChartJsonObj);
	}
	initWebsocket(ecgChartJsonObj,$(bedDiv).attr("mac"),Bodystm.DataType.ECG);//01
}


function initWebsocket(chartJsonObj,mac,type){//ecgChartJsonObj
	if(!window.WebSocket){  
	      window.WebSocket = window.MozWebSocket;  
	  }  
	  if(window.WebSocket){  
		  var ws=new WebSocket("ws://localhost:4000");  
		  chartJsonObj.ws=ws;
		  ws.onmessage = function(event){   
			  /*if(type==Bodystm.DataType.RESP)
				  console.log(event.data);*/
			  var ecgArr=event.data.split('/')[3].split(',');//.replace(/E-/g,'')
			  for(var i=0;i<ecgArr.length;i++){
				  chartJsonObj.dataTemp.push(ecgArr[i]);
			  }
//			  console.log("接收:" + event.data);
//			  console.log("接收:" + ecgArr);
	      };  
	   
	      ws.onopen = function(event){  
	            console.log("WebSocket 连接已建立");  
	            //send("/mac:FFFFFFFFFFFF");
	            sendMsgByWs(ws,"/connectws/"+type+"/"+mac);
	      };  
	   
	      ws.onclose = function(event){  
	    	  console.log("WebSocket 连接已关闭");  
	      };  
	  }else{  
	        alert("浏览器不支持WebSocket协议");  
	  } 	
}
/**
 * 初始化接收波形数据的ws
 * 此方法血压和血氧共用
 * @param ecgChartJsonObj
 * @param mac
 * @param type
 */
function initWebsocket4Oxiemetry(ecgChartJsonObj,mac,type){
	if(!window.WebSocket){  
	      window.WebSocket = window.MozWebSocket;  
	  }  
	  if(window.WebSocket){  
		  var ws=new WebSocket("ws://localhost:4000");  
		  ecgChartJsonObj.ws=ws;
		  ws.onmessage = function(event){ 
//			  console.log(event.data);
			  var arrTemp=event.data.split('/');
			  var ecgArr=arrTemp[3].split(',');//.replace(/E-/g,'')
			  for(var i=0;i<ecgArr.length;i++){
				  ecgChartJsonObj.dataTemp.push(ecgArr[i]);
			  }
			  ecgChartJsonObj.max=parseFloat(arrTemp[4]);
			  ecgChartJsonObj.min=parseFloat(arrTemp[5]);
//			  console.log("接收:" + event.data);
	      };  
	   
	      ws.onopen = function(event){  
	            console.log("WebSocket 连接已建立");  
	            //send("/mac:FFFFFFFFFFFF");
	            sendMsgByWs(ws,"/connectws/"+type+"/"+mac);
	      };  
	   
	      ws.onclose = function(event){  
	    	  console.log("WebSocket 连接已关闭");  
	      };  
	  }else{  
	        alert("浏览器不支持WebSocket协议");  
	  } 	
}
/**
 * 通过ws向服务器发送消息
 * @param ws websocket对象
 * @param message 要发送的消息
 */
function sendMsgByWs(ws,message){  
    if(!window.WebSocket){return;}
    if(ws.readyState == WebSocket.OPEN){  
        ws.send(message);  
        console.log("发送:" + message);  
    }else{  
        alert("WebSocket连接建立失败");
    }  
}
/**
 * 根据各个参数计算波形图中x轴最大坐标值
 * @param screenResolutionX 屏幕分辨率——横向
 * @param screenWidth 屏幕宽度，单位为mm
 * @param vWaveform 波形走速,单位为mm/s
 * @param chartAreaWidth 绘图区域宽度，单位为mm
 * @param chartAreaWidth 绘图区域宽度，单位为px
 * @param pointNumPerSecond 每秒从后台获取的数据点数量
 * @returns {Number} x轴最大横坐标
 */
function calChartXmax(screenResolutionX,screenWidth,vWaveform,chartAreaWidth,pointNumPerSecond){
	//屏幕每mm对应的像素数量
	var pxNumPerMm=screenResolutionX/screenWidth;
	//绘图区域占用的对应的像素数量
	//var chartAreaPxNum=chartAreaWidth*pxNumPerMm;
	var chartAreaPxNum=chartAreaWidth;
	//波形每秒走过的像素数量
	var pxNumPerSecond=vWaveform*pxNumPerMm;
	//波形图中每个单位横坐标对应的像素数量
	var pxNumPerX=pxNumPerSecond/pointNumPerSecond;
	//波形图x轴最大值
	var xMax=chartAreaPxNum/pxNumPerX;
	return xMax;
}
/**
 * 默认一像素绘制一个点的情况下获取目标采样率
 * @param screenResolutionX 屏幕分辨率——横向
 * @param screenWidth 屏幕宽度，单位为mm
 * @param vWaveform 波速
 * @returns {Number} 目标采样率
 */
function getTargetSampleRate(screenResolutionX,screenWidth,vWaveform){
	//屏幕每mm对应的像素数量
	var pxNumPerMm=screenResolutionX/screenWidth;
	return Math.round(vWaveform*pxNumPerMm);
}
function getChartXmax(screenResolutionX,screenWidth,chartAreaWidth){
	//屏幕每mm对应的像素数量
	var pxNumPerMm=screenResolutionX/screenWidth;
	return Math.round(chartAreaWidth*pxNumPerMm);
}